<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="8em">
      <el-form-item label="区域代理" prop="agent">
        <el-select v-model="form.agent" placeholder="选择区域代理">
          <el-option
            v-for="item in regionalAgentStore.list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户" prop="user">
        <el-select v-model="form.user" placeholder="选择用户">
          <el-option
            v-for="item in userProfileStore.list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="联系人名称" prop="contact_name">
        <el-input v-model="form.contact_name" placeholder="请输入联系人名称" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contact_phone">
        <el-input v-model="form.contact_phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="联系人邮箱" prop="contact_email">
        <el-input v-model="form.contact_email" placeholder="请输入联系人邮箱" />
      </el-form-item>
      <el-form-item label="是否有效" prop="is_active">
        <el-switch v-model="form.is_active" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio value="approve">通过</el-radio>
          <el-radio value="reject">拒绝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="营业执照" prop="business_license_url">
        <el-upload
          v-model:file-list="fileList1"
          :limit="1"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleBeforeUpload1"
          :before-remove="handleBeforeRemove1"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="身份证正面" prop="id_card_1">
        <el-upload
          v-model:file-list="fileList2"
          :limit="1"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleBeforeUpload2"
          :before-remove="handleBeforeRemove2"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="身份证反面" prop="id_card_2">
        <el-upload
          v-model:file-list="fileList3"
          :limit="1"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleBeforeUpload3"
          :before-remove="handleBeforeRemove3"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="form.status == 'reject'" label="拒绝原因" prop="reason">
        <el-input
          v-model="form.reason"
          placeholder="请输入拒绝原因"
          type="textarea"
          :rows="5"
          resize="none"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="supplierApplyStore.loading.create || supplierApplyStore.loading.update"
          @click="handleConfirm"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineModel } from "vue";
import { useSupplierApplyStoreHook } from "@/store/modules/supplier/apply";
import { useUserProfileStoreHook } from "@/store/modules/user/profile";
import { useRegionalAgentStoreHook } from "@/store/modules/user/regional-agent";
import { SupplierApplyForm } from "@/api/supplier/apply";
import { cloneDeep } from "lodash-es";
import { UploadFile, UploadFiles, UploadRawFile } from "element-plus";
import { getImageFileFromUrl } from "@/utils";

const supplierApplyStore = useSupplierApplyStoreHook();

const userProfileStore = useUserProfileStoreHook();

const regionalAgentStore = useRegionalAgentStoreHook();

export type FormType = "add" | "edit";

export interface Props {
  type: FormType;
  form?: SupplierApplyForm;
}

const visible = defineModel({ type: Boolean, default: false });

const emits = defineEmits(["confirm"]);

const props = defineProps<Props>();

const formRef = ref();

const defaultForm: SupplierApplyForm = {
  name: "",
  contact_name: "",
  contact_phone: "",
  contact_email: "",
  is_active: true,
  agent: "",
  user: "",
  status: "approve",
  business_license_url: "",
  id_card_1: "",
  id_card_2: "",
  reason: "",
};

const form = reactive<Partial<SupplierApplyForm>>(cloneDeep(defaultForm));

const fileList1 = ref<any[]>([]);
const fileList2 = ref<any[]>([]);
const fileList3 = ref<any[]>([]);

const rules = {
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "change",
    },
  ],
  user: {
    required: true,
    message: "请选择用户",
    trigger: "change",
  },
  contact_name: [
    {
      required: true,
      message: "请输入联系人名称",
      trigger: "change",
    },
  ],
  contact_phone: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "change",
    },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "change",
    },
  ],
  contact_email: [
    {
      required: true,
      message: "请输入联系人邮箱",
      trigger: "change",
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱地址",
      trigger: "change",
    },
  ],
  business_license_url: [
    {
      required: true,
      message: "请上传营业执照",
      trigger: "change",
    },
  ],
  id_card_1: [
    {
      required: true,
      message: "请上传身份证正面",
      trigger: "change",
    },
  ],
  id_card_2: [
    {
      required: true,
      message: "请上传身份证反面",
      trigger: "change",
    },
  ],
};

const title = computed(() => {
  return props.type === "add" ? "新增" : "编辑";
});

watch(visible, async (val) => {
  if (val) {
    await userProfileStore.fetchUserProfileList({ page: 1, size: 9999 });
    await regionalAgentStore.fetchList({ page: 1, size: 9999 });
    if (props.type === "edit") {
      Object.assign(form, props.form);
      fileList1.value = [{ url: form.business_license_url, uid: Date.now() }];
      form.business_license_url = await getImageFileFromUrl(
        form.business_license_url as string,
        "business_license_url.png"
      );
      fileList2.value = [{ url: form.id_card_1, uid: Date.now() }];
      form.id_card_1 = await getImageFileFromUrl(form.id_card_1 as string, "id_card_1.png");
      fileList3.value = [{ url: form.id_card_2, uid: Date.now() }];
      form.id_card_2 = await getImageFileFromUrl(form.id_card_2 as string, "id_card_2.png");
    }
  } else {
    Object.assign(form, cloneDeep(defaultForm));
    formRef.value.resetFields();
    fileList1.value = [];
    fileList2.value = [];
    fileList3.value = [];
  }
});

function handleBeforeUpload1(file: UploadFile, files: UploadFiles) {
  form.business_license_url = file.raw;
}

function handleBeforeRemove1(file: UploadFile, files: UploadFiles) {
  form.business_license_url = "";
  return true;
}

function handleBeforeUpload2(file: UploadFile, files: UploadFiles) {
  form.id_card_1 = file.raw;
}

function handleBeforeRemove2(file: UploadFile, files: UploadFiles) {
  form.id_card_1 = "";
  return true;
}

function handleBeforeUpload3(file: UploadFile, files: UploadFiles) {
  form.id_card_2 = file.raw;
}

function handleBeforeRemove3(file: UploadFile, files: UploadFiles) {
  form.id_card_2 = "";
  return true;
}

function handleConfirm() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (props.type === "add") {
        await supplierApplyStore.fetchCreate(form);
      } else {
        await supplierApplyStore.fetchUpdate(form);
      }
      visible.value = false;
      emits("confirm");
    }
  });
}
</script>

<style scoped lang="scss"></style>
